import axios from 'axios';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import Seo from '@/core/components/Seo';
import dynamic from 'next/dynamic';
import { getNameFromSlug } from '@/core/utils/slug';
import { capitalizeEachWord } from '../../utils/capializeFIrstWord';

const BasicLayout = dynamic(() =>
  import('@/core/components/layouts/BasicLayout')
);
const ProductSearch = dynamic(() =>
  import('@/lib/product/components/ProductSearch')
);

export default function FindPage() {
  const route = useRouter();
  const [result, setResult] = useState(null);
  const [query, setQuery] = useState(null);

  const slugRaw = route.query.slug || null;
  console.log(slugRaw);

  // const cleanKey = slugRaw ? getNameFromSlug(slugRaw) : '';
  // console.log(cleanKey);
  const readableSlug = capitalizeEachWord(slugRaw);

  const getSearchKeyData = async (clean) => {
    try {
      const res = await axios(
        `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/searchkey?url=${clean}&from=searchkey`
      );

      setResult(res?.data?.response?.docs?.[0] || null);
    } catch (e) {
      console.error('Fetching searchkey failed:', e);
    }
  };

  useEffect(() => {
    if (!route.isReady) return;
    if (!slugRaw) return;

    getSearchKeyData(slugRaw);
  }, [route.isReady, slugRaw]);

  useEffect(() => {
    if (result) {
      const ids = result.product_ids_is || [];

      setQuery({
        ids: ids.join(','),
        from: 'searchkey',
      });
    }
  }, [result]);

  return (
    <BasicLayout>
      <Seo
        title={`Beli ${readableSlug} Original & Harga Terjangkau - indoteknik.com`}
        description={`Beli ${readableSlug} Kirim Jakarta Surabaya Semarang Makassar Manado Denpasar.`}
        additionalMetaTags={[
          {
            property: 'keywords',
            content: `Beli ${readableSlug}, harga ${readableSlug}, ${readableSlug} murah`,
          },
        ]}
        canonical={`${process.env.NEXT_PUBLIC_SELF_HOST}${route.asPath}`}
      />

      {query && <ProductSearch query={query} prefixUrl={route.asPath} />}
    </BasicLayout>
  );
}
